package cog.support.util.map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/** 
 * 定时清除的map，此Map用于左右的对象只能通过定时来清除
 * 所有通过put方法加入的对象都在一定的时间内会被清除
 *
 * @author 陈杰
 * @since 2017/7/4 21:28
 *
 * Copyright ChenJie(wuzhiyun@aliyun.com)
 */  
  
public class TimedCacheHashMap<K, V> extends ConcurrentHashMap<K, V> {
    private Logger logger = LoggerFactory.getLogger(TimedCacheHashMap.class);
    /**
     * clear thread pool
     * */
    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    /**
     * 失效时间
     * */
    private long cacheTimeout;

    public TimedCacheHashMap(long cacheTimeout){
        this.cacheTimeout = cacheTimeout;
    }


    public class ClearThread implements Runnable{
        private K clearKey;

        public ClearThread(K k){
            this.clearKey = k;
        }

        public void run(){
            remove(clearKey);
            logger.info("<定时清除>  清除Map的Key为{}",this.clearKey);
        }
    }


    @Override
    public V put(K key, V value) {
        //提交线程，定时处理
        scheduledExecutorService.schedule(new ClearThread(key),this.cacheTimeout, TimeUnit.MILLISECONDS);
        return super.put(key, value);
    }

    @Override
    public V remove(Object key) {
        return null;
    }

    @Override
    public void clear() {
    }

    @Override
    public boolean remove(Object key, Object value) {
        return false;
    }
}